<template>
  <div>
    <p class="text-lg font-bold">进货单</p>
    <vxe-form
      title-colon
      ref="formRef"
      title-align="right"
      title-width="100"
      @submit="submitEvent"
      @reset="resetEvent($event)"
      :data="formData"
      :rules="formRules"
    >
      <vxe-form-gather span="24">
        <vxe-form-item title="办理人" field="user_id" span="4">
          <template #default="{ data }">
            <vxe-select v-model="data.user_id" placeholder="请选择办理人">
              <vxe-option
                v-for="(g, index) in searchTableOpt.userOpt"
                :label="g.label"
                :value="g.id"
                :key="index"
              >
              </vxe-option>
            </vxe-select>
          </template>
        </vxe-form-item>
        <vxe-form-item title="日期" field="purchase_date" span="4">
          <template #default="{ data }">
            <vxe-input
              v-model="data.purchase_date"
              placeholder="请选择日期"
              type="datetime"
              transfer
              formatter="formatDate"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item title="单据编号" field="purchase_order_no" span="4">
          <template #default="{ data }">
            <vxe-input
              v-model="data.purchase_order_no"
              placeholder="请输入单据编号"
            ></vxe-input>
          </template>
        </vxe-form-item>
        <vxe-form-item title="食材" field="receipt_items" span="24">
          <template #default="{ data }">
            <vxe-toolbar ref="toolbarRef" print export>
              <template #buttons>
                <vxe-button status="primary" @click="addReceiptItem(-1)"
                  >空白新增</vxe-button
                >
                <vxe-button @click="removeSelectReceiptItem"
                  >删除选中</vxe-button
                >
                <vxe-button status="primary" @click="pickTemplate"
                  >模板导入</vxe-button
                >
              </template>
            </vxe-toolbar>
            <!--              table-->
            <vxe-table
              border
              show-overflow
              show-footer
              keep-source
              :print-config="{
                sheetName: `${formData.purchase_order_no}`,
              }"
              :export-config="{
                filename: `${formData.purchase_order_no}`,
              }"
              :is-hover="true"
              :edit-rules="validRules"
              ref="xTable"
              :column-config="{ resizable: true }"
              min-height="200"
              :data="formData.purchaseorder_items"
              :footer-method="footerMethod"
              :edit-config="{
                trigger: 'click',
                mode: 'row',
                showStatus: true,
              }"
            >
              <vxe-column type="checkbox" width="60"> </vxe-column>
              <vxe-column
                field="supplier_name"
                title="供应商"
                sortable
                :edit-render="{
                  autofocus: '.vxe-input--inner',
                  defaultValue: '默认的名字',
                }"
              >
                <template #edit="{ row }">
                  <vxe-select
                    v-model="row.supplier_name"
                    placeholder="请选择供应商"
                    filterable
                    @change="supplierChange(row, $event)"
                  >
                    <vxe-option
                      v-for="(g, index) in searchTableOpt.supplierOpt"
                      :label="`${g.label},id:${g.id}`"
                      :value="g.label"
                      :key="index"
                    >
                    </vxe-option>
                  </vxe-select>
                </template>
              </vxe-column>

              <vxe-column
                field="supplier_id"
                title="供应商id"
                sortable
                :edit-render="{
                  autofocus: '.vxe-input--inner',
                  defaultValue: '默认的名字',
                }"
              >
                <template #edit="{ row }">
                  <vxe-input
                    disabled
                    v-model="row.supplier_id"
                    type="text"
                  ></vxe-input>
                </template>
              </vxe-column>
              <vxe-column
                field="material_name"
                title="食材名称"
                sortable
                :edit-render="{
                  autofocus: '.vxe-input--inner',
                  defaultValue: '默认的名字',
                }"
              >
                <template #edit="{ row }">
                  <!--                    使用懒加载，带搜索功能-->
                  <vxe-select
                    v-model="row.material_name"
                    placeholder="请选择商品"
                    filterable
                    @change="materialChangeName(row, $event)"
                  >
                    <vxe-option
                      v-for="(g, index) in searchTableOpt.materialOpt"
                      :label="g.name"
                      :value="g.name"
                      :key="index"
                    >
                    </vxe-option>
                  </vxe-select>
                </template>
              </vxe-column>

              <vxe-column
                field="material_id"
                title="食材id"
                sortable
                :edit-render="{
                  autofocus: '.vxe-input--inner',
                  defaultValue: '默认的名字',
                }"
              >
                <template #edit="{ row }">
                  <vxe-input disabled placeholder="请输入id"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column
                field="unit"
                title="单位"
                sortable
                :edit-render="{
                  autofocus: '.vxe-input--inner',
                  defaultValue: '默认的名字',
                }"
              >
                <template #edit="{ row }">
                  <vxe-input disabled v-model="row.unit"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column
                field="qty"
                title="数量"
                sortable
                :edit-render="{
                  autofocus: '.vxe-input--inner',
                  defaultValue: '',
                }"
              >
                <template #edit="{ row }">
                  <!--                    使用懒加载，带搜索功能-->
                  <vxe-input
                    v-model="row.qty"
                    type="number"
                    @change="qtyChange(row, $event)"
                  ></vxe-input>
                </template>
              </vxe-column>
              <vxe-column
                field="unit_price"
                title="单价"
                sortable
                :edit-render="{
                  autofocus: '.vxe-input--inner',
                  defaultValue: '默认的名字',
                }"
              >
                <template #edit="{ row }">
                  <vxe-input disabled v-model="row.unit_price"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column
                field="memo"
                title="备注"
                sortable
                :edit-render="{
                  autofocus: '.vxe-input--inner',
                  defaultValue: '默认的名字',
                }"
              >
                <template #edit="{ row }">
                  <!--                    使用懒加载，带搜索功能-->
                  <vxe-input v-model="row.memo"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column title="金额（元）" field="amount" sortable>
                <template #default="{ row }">
                  <span>{{ countAmount(row) }}</span>
                </template>
              </vxe-column>
            </vxe-table>
            <!--              table-->
          </template>
        </vxe-form-item>

        <vxe-form-gather span="16">
          <vxe-form-item title="总金额" field="amount" span="4">
            <template #default="{ data }">
              <vxe-input
                v-model="formData.amount"
                placeholder="请输入金额"
              ></vxe-input>
            </template>
          </vxe-form-item>
        </vxe-form-gather>
      </vxe-form-gather>

      <vxe-form-item align="left" span="24">
        <template #default>
          <vxe-button
            type="submit"
            icon="vxe-icon-save"
            status="primary"
            content="提交"
          ></vxe-button>
          <vxe-button
            type="reset"
            icon="vxe-icon-undo"
            content="重置"
          ></vxe-button>
        </template>
      </vxe-form-item>
    </vxe-form>

    <DraggableModal
      v-model:open="showEditPopup"
      :width="'1400px'"
      title="模板选择"
      :keyboard="false"
      :footer="false"
    >
      <vxe-table
        border
        show-overflow
        keep-source
        :is-hover="true"
        :column-config="{ resizable: true }"
        min-height="200"
        :data="purchaseTemplates"
      >
        <vxe-column field="id" title="模板id" sortable> </vxe-column>
        <vxe-column field="name" title="模板名称" sortable> </vxe-column>

        <vxe-column field="action" title="操作" sortable>
          <template #default="{ row }">
            <a-button type="primary" @click="importAction">导入</a-button>
            <a-button type="link" @click="showTemplate(row)">查看</a-button>
          </template>
        </vxe-column>
      </vxe-table>
      <a-collapse v-model:activeKey="collapseKey">
        <a-collapse-panel header="模板数据" key="1">
          <vxe-table
            border
            show-overflow
            keep-source
            :is-hover="true"
            :column-config="{ resizable: true }"
            min-height="200"
            :data="materialData"
          >
            <vxe-column field="id" title="货品id" sortable> </vxe-column>
            <vxe-column field="name" title="名称" sortable> </vxe-column>
            <vxe-column field="unit" title="单位" sortable> </vxe-column>
            <vxe-column field="spec" title="规格" sortable> </vxe-column>
            <vxe-column field="price" title="价格" sortable> </vxe-column>
          </vxe-table>
        </a-collapse-panel>
      </a-collapse>
    </DraggableModal>
  </div>
</template>

<script setup lang="ts">
import useRuleStore from "@/store/modules/rule";
import Api from "@/api/backend/api";
import XEUtils from "xe-utils";
import { message } from "ant-design-vue";
import { VXETable } from "vxe-table";
const activeKey = ref("1");
const { gridOptions } = useMPurchaseOrder();
const xGrid = ref();
const toolbarRef = ref();

const ruleStore = useRuleStore();
const router = useRouter();
const gridEvent: VxeGridListeners<RowVO> = {
  proxyQuery() {
    console.log("数据代理查询事件");
    const grid = xGrid.value;
  },
  proxyDelete() {
    console.log("数据代理删除事件");
  },
  proxySave() {
    console.log("数据代理保存事件");
  },
};

const userOpt = ref([]);

const xTable = ref();

const formRef = ref();
// region 表格数据
const receipt_items = ref([
  {
    id: null,
    supplier_id: null,
    supplier_name: "",
    purchase_order_id: null,
    bill_no: null,
    material_id: null,
    material_name: "",
    quantity: 0,
    serial_no: null,
    unit_price: null,
    amount: 0,
    discount_amount: 1,
    memo: null,
  },
]);

// 定义一个非响应式数据add_receipt_items
let add_receipt_items = {
  id: null,
  supplier_id: null,
  supplier_name: null,
  purchase_order_id: null,
  receipt_type: 1, //进货
  material_id: null,
  material_name: "",
  qty: 0,
  serial_no: 0,
  unit_price: 0,
  amount: 0,
  discount_amount: 1,
  memo: null,
};

let formData = reactive({
  purchase_date: XEUtils.toDateString(new Date(), "yyyy-MM-dd HH:mm:ss"),
  purchase_order_no:
    "JHDD-" + XEUtils.toDateString(new Date(), `yyyyMMddHHmmss`),
  status: 1,
  user_id: null,
  quantity: 0,
  amount: 0,
  order_type: 1,
  purchaseorder_items: [],
});

const removeSelectReceiptItem = (row) => {
  const $table = xTable.value;
  if ($table) {
    $table.removeCheckboxRow();
  }
};
const searchTableOpt = ref({
  supplierOpt: [],
  materialOpt: [],
  userOpt: [],
});

onMounted(async () => {
  const materialOpt = await Api.materialController.option({
    filters: {
      supplier_id: searchTableForm.value.supplier_id,
    },
  });
  const useropt = await Api.userController.option();
  const supplieropt = await Api.supplierController.option({
    filters: {
      id: null,
    },
  });
  searchTableOpt.value.materialOpt = materialOpt;
  searchTableOpt.value.userOpt = useropt;
  searchTableOpt.value.supplierOpt = supplieropt;
  const $table = xTable.value;
  const $toolbar = toolbarRef.value;
  if ($table && $toolbar) {
    $table.connect($toolbar);
  }
});

const searchTableForm = ref({
  supplier_id: null,
  product_id: null,
});

// 这三个方法会相互联动
const supplierChange = async (row, event) => {
  row["supplier_id"] = searchTableOpt.value.supplierOpt.filter(
    (item) => item.label == row.supplier_name
  )[0]["id"];
  searchTableOpt.value.materialOpt = await Api.materialController.option({
    filters: {
      supplier_id: row["supplier_id"],
    },
  });
  row["material_name"] = "";
  //同时
  //同时
  row["unit_price"] = 0;
  row["unit"] = 0;
  row["material_id"] = 0;
};

const materialChangeName = async (row, event) => {
  const material = searchTableOpt.value.materialOpt.filter(
    (item) => item.name == row.material_name
  )[0];
  row["material_name"] = material["name"];
  //同时
  row["unit_price"] = material["price"];
  row["unit"] = material["unit"];
  row["material_id"] = material["id"];
  row["serial_no"] = material["code"];
};

// 输入商品数量时
const qtyChange = (row, event) => {
  row.amount = row.qty * row.unit_price;
};

//直接新增
const addReceiptItem = async (row) => {
  const $table = xTable.value;
  if ($table) {
    const record = add_receipt_items;
    const { row: newRow } = await $table.insertAt(record, row);
    await $table.setEditCell(newRow, "supplier_id");
  }
};

// 复制新增
const copyReceiptItem = async (row) => {
  const $table = xTable.value;
  if ($table) {
    receipt_items.value[0]["_X_ROW_KEY"] = null;
    const record = receipt_items.value[0];
    const { row: newRow } = await $table.insertAt(record, row);
    await $table.setEditCell(newRow, "goods_id");
  }
};

const sumNum = (list: ReceiptItemModel[], field: string) => {
  let count = 0;
  list.forEach((item) => {
    count += item[field];
  });
  return count;
};

const countAmount = (row: ReceiptItemModel) => {
  row.qty = +row.qty;
  let mount = row.unit_price * row.qty;

  return mount;
};

const countAllAmount = (data: ReceiptItemModel[]) => {
  let count = 0;
  data.forEach((row) => {
    count = count + countAmount(row);
  });
  return count;
};


// 表格校验
const validRules = ref<VxeTablePropTypes.EditRules>({
  supplier_name: [{ required: true, message: "供应商必须填写" }],
  material_name: [{ required: true, message: "商品名称必须填写" }],
  unit: [{ required: true, message: "单位必须填写" }],
  qty: [{ required: true, message: "数量必须填写" }],
});

const footerMethod: VxeTablePropTypes.FooterMethod<ReceiptItemModel> = ({
  columns,
  data,
}) => {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return "合计";
      }
      if (columnIndex === 1) {
        //表单提交时会自动触发该事件。这个时候需要更新formData中的amount
        let count = countAllAmount(data);
        formData.amount = count;
        return `共 ${count} 元`;
      }
      if (columnIndex === 6) {
        formData.quantity = sumNum(data, "qty");
        return `数量： 共 ${sumNum(data, "qty")}`;
      }
      return "-";
    }),
  ];
};
// endregion
const formRules = ref<VxeFormPropTypes.Rules>({
  supplier_name: [{ required: true, content: "请选择供货单位" }],
  user_id: [
    {
      required: true,
      content: "请选择经手人",
    },
  ],
  record_date: [{ required: true, content: "请选择制单日期" }],
});

// 提交表单
const submitEvent = async () => {
  const $table = xTable.value;
  //验证表格中的数据，如果失败则返回
  let error = await $table.validate();
  if (error) {
    message.error("数据错误，请检查");
    return;
  }
  const { tableData } = $table.getTableData();
  if (tableData.length == 0) {
    message.error("请添加商品，请检查");
    return;
  }
  formData.purchaseorder_items = tableData;

  // 等于子项目数量之和
  formData.quantity = +formData.quantity;
  formData.amount = +formData.amount;
  formData.purchaseorder_items.forEach((item) => {
    item.qty = +item.qty;
    item.material_id = +item.material_id;
    item.unit_price = +item.unit_price;
    item.amount = +item.amount;
  });

  await Api.mPurchaseOrderController.store(formData);
  // 清空表单，
  $table.clearData();
  // 清空表格
  router.go(-1);
};
const resetEvent = (e) => {
  formData.purchaseorder_items = [];
  message.success("重置成功");
};
const detail = (row) => {
  router.push(`/inventory/material/purchaseorder/${row.id}/receiptitem`);
};
const del = async (row) => {
  await Api.mOrderController.destroy({
    id: row.id,
  });
};

//模板导入
const showEditPopup = ref(false);
const collapseKey = ref("1");
const purchaseTemplates = ref([]);
const materialData = ref([]);
const pickTemplate = async () => {
  showEditPopup.value = true;
  purchaseTemplates.value = await Api.mPurchasetemplateController.index();
};
const showTemplate = async (row)   => {
  materialData.value = await Api.mPurchasetemplateController.material({
    id: row.id,
  });
  collapseKey.value = "1";
};

const importAction = async () => {
  if (materialData.value.length == 0) {
    return message.error("请先查询数据后导入");
  }
  let insertData = materialData.value.map((item) => {
    return {
      supplier_id: item.supplier_id,
      supplier_name: item.supplier.name,
      receipt_type: 1,
      material_id: item.id,
      material_name: item.name,
      unit_price: item.price,
      unit: item.unit,
    };
  });
  const $table = xTable.value;
  if ($table) {
    const { row: newRow } = await $table.insertAt(insertData, -1);
    const { tableData } = $table.getTableData();
  }
};
</script>

<style></style>
